import { queryMenus, queryContent } from '@/api/base';
import { postLogout } from '@/api/login.js';
import { commonDownload } from '@/api/common';
import routerPageMap from '@/router/routerPageMap';
import { generateAsyncRouter } from '@/router/util';
import config from '@/config/index';
import store from '@/store/store';
import { getInfo } from '@/api/login';
import { BaseStatusEnum } from '../enum/enum';
import { storageGet, storageSet } from '@/appBase/zkStorage';
import { familyMemberTypeDic, gradeDic, majorDic, policyIdentityDic, sexDic } from './dic';
import allIcon from './icons';

/**
* 拉取动态路由信息
*/
export function getDynamicRouter(store) {
    const sortId = (a, b) => {
        return a.sort - b.sort;//由低到高
    }
    if (config.env == config.EnvEnum.DEV) {
        // 开发阶段拉取本地模拟全量的导航菜单配置
        return Promise.all([import('@/router/dynamicRouterMap')]).then((res) => {
            const result = res[0];
            const arr = res[0].default;
            return generateAsyncRouter(arr, routerPageMap);
        });
    }
    return queryMenus().then((result) => {
        const createTreeNode = (menusNode,pNode)=>{
            let { path, meta,children} = menusNode;
            if (!meta) {
                meta = {};
            }
            if (pNode&&path.indexOf('/')!=0) {
                // 相对路径改为绝对路径
                path =`${pNode.path}/${path}`;
            }
            const node = {
                path,
                meta: {
                    title:meta.title,
                    icon:allIcon[meta.icon + 'Icon'] || meta.icon,
                    link:meta.link
                }
            }
            if (children) {
                node.children = children.map(i=>createTreeNode(i,node));
            }
            return node;
        }
        const arr = result.map(i=>createTreeNode(i,null));
        return generateAsyncRouter(arr, routerPageMap);
    });
}

/**
 * 退出登录
 * @param {*} ctx 
 * @param {Boolean} force 是否强制退出登录(不需服务端知晓的情况)
 * @returns 
 */
export function logout(ctx, force) {
    let prom = Promise.resolve();
    if (!force) prom = postLogout();
    const handleFunc = ()=>{
        store.commit('UpdateToken', null);
        store.commit('ClearNowUserInfo');
        ctx && ctx.$store.commit('UpdateDynamicRouter', null);
        setTimeout(() => {
            if (window.location.href.indexOf('#') > -1 && window.location.href.indexOf('_tk') < 0) {
                window.location.href = window.location.href.split('#')[0]
            } else {
                window.location.href = window.location.origin;
            }
        }, 500)
    }
    return prom.then((result) => {
        handleFunc();
        return result;
    }).catch((err)=>{
        handleFunc();
    })
}

export function appStateInit() {
    getInfo().then((result) => {
        const nowUserInfo = result.user;
        nowUserInfo.permissions = result.permissions;
        nowUserInfo.hasVal = true;
        store.commit('UpdateNowUserInfo', nowUserInfo);
    });
    sexDic.init();
    majorDic.init();
    gradeDic.init();
    policyIdentityDic.init();
    familyMemberTypeDic.init();
    // // 查询公司信息
    // queryCorpInfomation().then((result) => {});
    // // 更新医院等级列表
    // queryHospitalGrade().then((result) => {});
    // // 更新医生职称
    // queryDoctorProfessional().then((result) => {});
    // // 更新医生职务
    // queryDoctorPost().then((result) => {});
    // // 更新医生职级
    // queryDoctorLevel().then((result) => {});
}

/**
 * 查询公司信息
 */
export function queryCorpInfomation() {
    // 版权信息
    return queryContent({ key: 'Public_CorpInfomation' }).then((result) => {
        if (!result) return;
        const contentText = result.contentText;
        config.copyright = contentText['zh_cn'].copyright;
        config.enCopyright = contentText['en'].copyright;
    });
}

/**
 * 检测该路径是否存在于路由中
 * @param {String} path 
 * @param {Array} routerArr 
 */
export function findRouterInRoute(path, routerArr) {
    let val = null;
    const array = routerArr;
    for (let index = 0, len = array.length; index < len; index++) {
        const item = array[index];
        if (item.path == path) {
            val == item;
            return val;
        }
        if (item.children) {
            val = findRouterInRoute(path, item.children);
            if (val) return val;
        }
    }
    return val;
}

/**
 * 获取当前用户信息
 * 
 * @return {{
 *      doctorId: "医生Id"
 *      id: "用户id", userType=1 时为医生 Id,此外为 operatorId
 *      teamId: '工作室 id'
 *      name: "工作室名称"
 *      userName: "用户名称"
 *      permission: "权限1,权限2"
 *      token: "token",
 *      userType:1 1.医生 2.运营人员,
 *      operatorId: 运营人员 Id
 * }}
 */
export function getNowUserInfo() {
    const nowUserInfo = store.state.nowUserInfo;
    return nowUserInfo && nowUserInfo.hasVal == true ? nowUserInfo : null;
}

/**
 * 获取常规状态选项列表
 * @param {Number} type 0.常规 1.带额外全部选项
 */
export function getStatusOpts(type) {
    const arr = [
        { label: BaseStatusEnum.toStr(BaseStatusEnum.ENABLE), value: BaseStatusEnum.ENABLE },
        { label: BaseStatusEnum.toStr(BaseStatusEnum.DISABLED), value: BaseStatusEnum.DISABLED }
    ];
    if (type == 1) {
        arr.unshift({ label: BaseStatusEnum.toStr(BaseStatusEnum.ALL), value: BaseStatusEnum.ALL });
    }
    return Promise.resolve(arr);
}

/**
 * 下载文件
 * @param fileName 文件名
 */
export function downloadFile(fileName) {
    window.location.href = `${config.apiRoot}${commonDownload}?fileName=${encodeURI(fileName)}`;
}